<template>
  <div class="translation-history">
    <el-button
      class="back-button"
      type="primary"
      icon="ArrowLeft"
      @click="goBack"
    >
      返回
    </el-button>
    <h2>翻译历史记录</h2>
    <div v-if="paginationTotal !== 0">
      <el-table
        :data="historyData"
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column prop="question" label="问题" min-width="40%">
          <template #default="scope">
            <div
              :class="['text-wrapper', { expanded: scope.row.expanded }]"
              :ref="
                (el) => {
                  if (el) questionRefs[scope.$index] = el;
                }
              "
            >
              {{ scope.row.question }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="translation" label="您的翻译" min-width="40%">
          <template #default="scope">
            <div
              :class="['text-wrapper', { expanded: scope.row.expanded }]"
              :ref="
                (el) => {
                  if (el) translationRefs[scope.$index] = el;
                }
              "
            >
              {{ scope.row.translation }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="score"
          label="评估分数"
          width="100"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.score }}
          </template>
        </el-table-column>
      </el-table>
      <div class="example-pagination-block">
        <div class="pagination-container">
          <el-pagination
            layout="prev, pager, next"
            :total="paginationTotal"
            :default-page-size="10"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
    <div v-else class="no-data">暂无翻译历史记录</div>
  </div>
</template>

<script setup>
import { httpClient } from "@/libs/http-client";
import router from "@/router";
import { ref, onMounted, onUnmounted, nextTick } from "vue";

const historyData = ref([]);

const questionRefs = ref([]);
const translationRefs = ref([]);
const paginationTotal = ref(0);

const handleRowClick = (row, column, event) => {
  row.expanded = !row.expanded;
  nextTick(() => {
    checkOverflow();
  });
};

const checkOverflow = () => {
  historyData.value.forEach((row, index) => {
    const questionEl = questionRefs.value[index];
    const translationEl = translationRefs.value[index];

    if (questionEl) {
      checkElementOverflow(questionEl, row);
    }

    if (translationEl) {
      checkElementOverflow(translationEl, row);
    }
  });
};

const checkElementOverflow = (element, row) => {
  // 临时移除 max-height 限制以获取完整高度
  element.style.maxHeight = "none";
  const scrollHeight = element.scrollHeight;
  element.style.maxHeight = "";

  const clientHeight = element.clientHeight;

  if (scrollHeight - 1 > clientHeight && !row.expanded) {
    element.classList.add("truncate");
  } else {
    element.classList.remove("truncate");
  }
};

// 添加防抖函数
const debounce = (fn, delay) => {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), delay);
  };
};

// 创建一个防抖版本的 checkOverflow
const debouncedCheckOverflow = debounce(checkOverflow, 200);

// 添加窗口大小变化的监听器
const handleResize = () => {
  debouncedCheckOverflow();
};

const handlePageChange = (page) => {
  console.log("Page changed:", page);
  loadHistoryData(page);
};

const loadHistoryData = (page) => {
  // 获取数据
  httpClient
    .get("translate/getTranslateRecord", {
      params: {
        pageNum: page,
        pageSize: 10,
      },
    })
    .then((data) => {
      historyData.value = [];
      console.log(data);
      data.records.forEach((item) => {
        historyData.value.push({
          question: item.question,
          translation: item.userAnswer,
          score: item.accuracy,
        });
      });
      paginationTotal.value = data.total;
    });
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  nextTick(() => {
    // 使用 setTimeout 确保在下一个事件循环中执行
    setTimeout(() => {
      checkOverflow();
    }, 0);
  });
  window.addEventListener("resize", handleResize);

  // 初始加载数据
  loadHistoryData(1);
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
.translation-history {
  padding: 20px;
}

.text-wrapper {
  min-height: 2.6em; /* 约两行文本的高度 */
  max-height: 2.6em; /* 约两行文本的高度 */
  line-height: 1.2;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.text-wrapper.truncate {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  position: relative;
}

.text-wrapper.truncate::after {
  content: "...";
  position: absolute;
  bottom: 0;
  right: 0;
  padding-left: 40px;
  background: linear-gradient(to right, transparent, white 50%);
}

.text-wrapper.expanded {
  max-height: none;
  -webkit-line-clamp: unset;
}

.text-wrapper.expanded::after {
  display: none;
}

.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.back-button {
  left: 20px;
  top: 20px;
}
.no-data {
  text-align: center;
  padding: 20px;
  font-size: 16px;
  color: #909399;
}
</style>
